import { message } from './index'
import store from '@/store'
import { LOGIN_OUT } from '@/store/mutation-types'
import router from './router'
import { WX_APP_ID, VERSION } from './config'

export const SUCCESS_CODE = 0 //成功
export const AUTH_INVALID = 401
export const AUTH_INVALID_2 = 403
export const ERROR_CODE = -9999 //系统异常

const AUTH_ERROR = [AUTH_INVALID, AUTH_INVALID_2]

export const setURL = (url, args) => {
    if (typeof url === 'undefined') {
        throw 'no url!'
    }
    if (!args) return url
    for (var i = 0; i < args.length; i++) {
        if (url.indexOf('{?}') < 0) {
            break
        }
        url = url.replace(/\{\?\}/, args[i] + '')
    }
    // 最后是否有/{?}
    if (url.lastIndexOf('/{?}') > -1) {
        url = url.substr(0, url.lastIndexOf('/{?}'))
    }
    return url
}

const COMMON_HEADER = {
    os: 4,
    version: VERSION,
    deviceCode: '',
    bundleId: 'com.wonderful.mart',
    channel: 'wonderful',
    clientId: WX_APP_ID
}

/**
 * option {
    loading: boolean true 菊花， false， 没有菊花（ 相当于无声请求）
    showMsg: 是否显示错误信息, 如果是
    loadingText: 请稍等...
    url: '' //可以传apiurl中的key, 也可以传整个url
    param: 作为post数据传过去，json对象或者字符串, 如果是字符串那么可能是body形式传过去，
    pathParam: 接口名称中可能会有参数 []从数组中传过来,
    method: //默认POST,
    type: '默认application/json', 'form': 'x-www-form-urlencoded',
    token: 测试用的token
  }
 返回 Promise
 */
let loginFlag = false
export const request = (url, option) => {
    url = setURL(url, option.pathParam)
    let hasLoading = option.loading
    if (hasLoading) {
        message.showLoading()
    }

    let data = option.param || {}

    let track = { ...COMMON_HEADER }
    if (store.state.pid) {
        track.pid = store.state.pid
    }
    if (store.state.channel) {
        track.channel = store.state.channel
    }
    if (store.state.adid) {
        track.adid = store.state.adid
    }
    if (store.state.clickId) {
        track.clickId = store.state.clickId
    }
    if (store.state.callback) {
        track.callback = store.state.callback
    }
    if (store.state.shareUserId) {
        track.pid = store.state.shareUserId
    }
    let header = {
        'content-type': 'application/json',
        track: JSON.stringify(track)
    }

    if (option.type == 'form') {
        header['content-type'] = 'x-www-form-urlencoded'
    }

    if (data.token) {
        header.Authentication = data.token
        delete data.token
    } else if (store.state.token) {
        header.Authentication = store.state.token
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            data: data,
            method: option.method ? option.method : 'POST',
            header: header,
            success: (res) => {
                if (hasLoading) {
                    message.hideLoading()
                }
                if (res.statusCode == 200) {
                    if (res.data.code == 0) {
                        resolve(res.data)
                    } else {
                        if (AUTH_ERROR.includes(res.data.code)) {
                            store.commit(LOGIN_OUT)
                        }
                        if (hasLoading || option.showMsg) {
                            message.error(res.data.msg)
                        }
                        reject(res.data)
                    }
                } else {
                    if (AUTH_ERROR.includes(res.statusCode)) {
                        if (loginFlag) return
                        loginFlag = true
                        store.commit(LOGIN_OUT)
                        router.login()
                        setTimeout(() => {
                            loginFlag = false
                        }, 1500)
                        reject(res)
                        return
                    }
                    if (hasLoading || option.showMsg) {
                        message.error('网络异常')
                    }
                    reject(res)
                }
            },
            fail: (res) => {
                if (hasLoading || option.showMsg) {
                    message.hideLoading()
                    message.error('网络异常')
                }
                reject(res)
            },
            complete: (res) => {
                uni.stopPullDownRefresh()
            }
        })
    })
}

export const post = (url, param, option = {}) => {
    return request(url, { ...option, param })
}

export const postL = (url, param, option = {}) => {
    return request(url, { loading: true,...option, param  })
}

export const get = (url, param, option = {}) => {
    option.method = 'GET'
    return post(url, param, option)
}

export const getL = (url, param, option = {}) => {
    option.method = 'GET'
    return postL(url, param, option)
}
